package com.taobao.askwho.db.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.taobao.askwho.db.base.MysqlRouteBase;
import com.taobao.askwho.po.UrlInfo;
import com.taobao.askwho.utils.DateUtil;

public class UrlInfoDao extends MysqlRouteBase {
	private static  Logger logger = Logger.getLogger(UrlInfoDao.class);
	
	public List<UrlInfo> getRecentlyUrl(int limit, int size) {
		final List<UrlInfo> list = new ArrayList<UrlInfo>();
		String sql = "SELECT * FROM url_info ORDER BY updatetime DESC LIMIT ?,?";
		try {
			this.query(sql, new Object[]{limit,size}, new SqlCallBack() {
				@Override
				public void readerRows(ResultSet rs) throws Exception {
					UrlInfo info = new UrlInfo();
					setValueForPo(info,rs);
					list.add(info);
				}
			});
		} catch (Exception e) {
			logger.error("",e);
		}
		return list;
	}
	
	public Map<String, UrlInfo> getUrlListByUuidList(List<String> uuidList) {
		//暂时做两次查询,把结果做合并
		String inStr = "";
		for(String uuid: uuidList) {
			inStr += "'" + uuid + "',";
		}
		if(uuidList.size() > 0)
			inStr = inStr.substring(0,inStr.length() - 1);
		else
			return new HashMap<String, UrlInfo>();		
		
		final Map<String, UrlInfo> map = new HashMap<String, UrlInfo>();
		String sql = "SELECT * FROM url_info where uuid in (" + inStr + ")";
		try {
			this.query(sql, new SqlCallBack() {
				@Override
				public void readerRows(ResultSet rs) throws Exception {
					UrlInfo info = new UrlInfo();
					setValueForPo(info,rs);
					map.put(info.getUuid(), info);
				}
			});
		} catch (Exception e) {
			logger.error("",e);
		}
		return map;
	}	
	
	public void addUrlInfo(UrlInfo info) throws SQLException {
		String sql = "INSERT INTO url_info(UUID,url_content,updatetime,createtime) VALUE (?,?,?,?)";
		this.execute(sql, new Object[]{info.getUuid(), info.getUrlContent(),
				info.getUpdateTime(), info.getCreateTime()});
	}
	
	public void deleteUrlInfo(String uuid) throws SQLException {
		String sql = "delete from url_info where uuid = ?";
		this.execute(sql, new Object[]{uuid});
	}	

	private void setValueForPo(UrlInfo urlInfo, ResultSet rs) throws SQLException {
		urlInfo.setUuid(rs.getString("uuid"));
		urlInfo.setUrlContent(rs.getString("url_content"));
		urlInfo.setCreateTime(new Date());	//FIXME 读取sql.date后，json显示有问题
		urlInfo.setUpdateTime(new Date());
		urlInfo.setCreateTimeStr(DateUtil.cutLastNumOfSqlTimeString(rs.getString("createtime")));
		urlInfo.setUpdateTimeStr(DateUtil.cutLastNumOfSqlTimeString(rs.getString("updatetime")));		
	}	
}
